const router = require('koa-router')();
const FormData = require('form-data');
const fs = require('fs');
const { formatDate } = require('../../config/formatDate.js');
const { getToken, UploadFileUrl, Addurl, Updateurl } = require('../../config/databaseapi.js');
// const { getLogo } = require('../../config/filetype.js');
const { getFileSize } = require('../../config/filesize.js');
const { v4: uuidv4 } = require('uuid');
router.post('/upload', async (ctx) => {
	console.log('调用上传文件接口');
	// 接收前端传递过来的文件
	const { file } = ctx.request.files;
	const { currentParentId, currentLocationName } = ctx.request.body;
	// console.log(currentListId);
	// console.log(currentLocationName);
	// 取文件的各项参数
	const createDate = new formatDate().getDate();                  //上传日期
	const type = file.mimetype;                                     //文件类型
	// const fileId = new getLogo().getURL(type);                     //文件ID
	const filePath = file.filepath;                                 //文件在koa服务器临时存储的路径
	const fileName = file.originalFilename;                         //文件名
	const fileSize = new getFileSize().getfilesize(file.size);      //文件大小
	const _id = uuidv4();
	const status = '0';
	const remark = '';
	// 云存储路径
	let cloudpath = ``;
	if(currentParentId===''){
		// console.log('根目录')
		cloudpath = `${fileName}`;
	}else{
		let arr = currentLocationName.split('/');
		cloudpath = `${arr[1]}/${fileName}`;
	}
	
	// 第一次云存储请求
	let res = await new getToken().posteve1(UploadFileUrl, cloudpath);
	const file_id = res.file_id;
	const obj = { createDate, fileName, type, fileSize, file_id, _id, status, remark, parentId:currentParentId };  //整合文件的参数,便于存入数据库
	// 编辑第二次云存储上传文件请求的请求体
	let formData = new FormData();
	//添加字段
	formData.append('key', cloudpath);
	formData.append('Signature', res.authorization);
	formData.append('x-cos-security-token', res.token);
	formData.append('x-cos-meta-fileid', res.cos_file_id);
	//添加文件
	formData.append('file', fs.createReadStream(filePath), {
		filename: fileName,
		contentType: 'application/octet-stream'
	});
	// 第二次云存储上传文件请求
	let res1 = await new getToken().posteve2(res.url, formData);
	if(res1){
		// 存数据库
		const query = `db.collection("study_materials").add({data:${JSON.stringify(obj)}})`;
		const dbres = await new getToken().posteve(Addurl, query);
		 
		// console.log('添加结果', dbres);
		fs.unlink(filePath,(err)=>{
			if(err){
				console.error('上传文件失败');
			}else{
				console.log('上传文件成功');
			}
		})
		if(dbres.errcode === 0){
			ctx.body = {msg:'文件上传成功,写入数据库成功',status:1}
		}else{
			ctx.body = {msg:'文件上传成功,写入数据库失败',status:0}
		}
	}else{
		ctx.body = {msg:'文件上传失败',status:0}
	}
})
module.exports = router.routes()